import mysql.connector
from mysql.connector import pooling
from typing import Dict, Optional


class DatabaseConfig:
    """数据库配置类，管理数据库连接池"""

    def __init__(self):
        self.config = {
            'host': 'localhost',
            'user': 'parking_admin',
            'password': 'secure_password',
            'database': 'parking_system',
            'port': 3306,
            'charset': 'utf8mb4'
        }
        self.pool = self._create_connection_pool()

    def _create_connection_pool(self) -> pooling.MySQLConnectionPool:
        """创建数据库连接池"""
        return pooling.MySQLConnectionPool(
            pool_name="parking_pool",
            pool_size=10,
            pool_reset_session=True,
            **self.config
        )

    def get_connection(self):
        """获取数据库连接"""
        try:
            return self.pool.get_connection()
        except mysql.connector.Error as e:
            print(f"数据库连接错误: {e}")
            raise

    def execute_query(self, query: str, params: Optional[Dict] = None, fetch: str = "all"):
        """
        执行查询语句
        :param query: SQL查询语句
        :param params: 查询参数
        :param fetch: 获取方式，"all"或"one"
        :return: 查询结果
        """
        connection = None
        cursor = None
        try:
            connection = self.get_connection()
            cursor = connection.cursor(dictionary=True)
            cursor.execute(query, params or ())

            if fetch == "all":
                result = cursor.fetchall()
            elif fetch == "one":
                result = cursor.fetchone()
            else:
                result = None

            return result
        except mysql.connector.Error as e:
            print(f"查询执行错误: {e}")
            raise
        finally:
            if cursor:
                cursor.close()
            if connection:
                connection.close()

    def execute_update(self, query: str, params: Optional[Dict] = None) -> int:
        """
        执行更新语句(INSERT, UPDATE, DELETE)
        :param query: SQL语句
        :param params: 参数
        :return: 受影响的行数
        """
        connection = None
        cursor = None
        try:
            connection = self.get_connection()
            cursor = connection.cursor()
            cursor.execute(query, params or ())
            connection.commit()
            return cursor.rowcount
        except mysql.connector.Error as e:
            if connection:
                connection.rollback()
            print(f"更新执行错误: {e}")
            raise
        finally:
            if cursor:
                cursor.close()
            if connection:
                connection.close()

# 单例模式的数据库配置实例
db_config = DatabaseConfig()